package com.task.scheduling.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program: facade-console
 * @description:存放执行中的task, 更新心跳计数用
 * @author: zhouliangliang
 * @create: 2018-11-29 18:10
 **/
public class TaskHolder {

    private static Logger log = LoggerFactory.getLogger(TaskHolder.class);
    private static Lock lock = new ReentrantLock();

    private static List<Long> list = new CopyOnWriteArrayList<>();

    private TaskHolder() {

    }

    public static void holdTask(Long id) {
        try {
            lock.lock();

            if(list.contains(id)) {
                log.info("任务, {} 已经在执行记录中", id);
            } else {
                list.add(id);
                log.info("任务，{}, 持有成功", id);
            }

        } catch (Exception e) {
            log.error("hold task error!" + e.getMessage(), e);
        } finally {
            lock.unlock();
        }
    }

    public static void removeTask(Long id) {
        try {
            lock.lock();
            log.info("任务，{}, 释放成功", id);
            list.remove(id);
        } catch (Exception e) {
            log.error("remove task error!" + e.getMessage(), e);
        } finally {
            lock.unlock();
        }
    }

    public static List getRunningTaskList(){
        return list;
    }
}
